<template>
    <div class="maintainexploitgroup" v-loading="state.loading">
        <el-card>
            <template #header>
				<div class="card-header clearfix">
                        <span class="headerTitle">{{router.currentRoute.value.meta.title}}</span>
                        <div class="floatRight">
                            <el-button type="primary" v-if="isAuthBtn('add')" @click="tabBtn('add','')"><i class="fa fa-send"></i>新增</el-button>
                        </div>
				</div>
			</template>
            <div>
                <div>
                    <div class="k-disply-inline-block" style="margin-right:10px;">
                        <el-input
                            v-model="state.key"
                            placeholder="请输入关键词查询"
                            clearable
                        ></el-input>
                    </div>
                    <el-button style="margin-left:10px;" @click="getGroupList(1)">查找</el-button>
                </div>
                <el-table
                    :data="state.dataList"
                    style="width: 100%; margin-bottom: 20px"
                    row-key="id" v-loading="state.tabloading"
                >
                    <el-table-column prop="id" label="id"  align="center" min-width="100" />
                    <el-table-column prop="config_name" label="KEY"  align="center"  min-width="200" />
                    <el-table-column prop="name" label="组合名称"  align="center" min-width="200"  />
                    <el-table-column prop="info" label="组合简介"  align="center" min-width="200"  />
                    <el-table-column fixed="right" label="操作" min-width="200" align="center">
                        <template #default="scope">
                            <el-button link type="primary" v-if="isAuthBtn('editor')" @click="tourl('/maintain/exploit/grouplist/'+scope.row.id)">数据列表</el-button>
                            <el-button link type="primary" v-if="isAuthBtn('editor')" @click="tabBtn('editor',scope.row)">编辑</el-button>
                            <el-button link type="primary" v-if="isAuthBtn('del')" @click="tabBtn('del',scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="pagination-block clearfix">
				<div class="pagination-right">
					<el-pagination
					v-model:current-page="state.pages.pno"
					v-model:page-size="state.pages.pageSize"
					:page-sizes="[10, 50, 100, 200]"
					layout="total, sizes, prev, pager, next, jumper"
					:total="state.pages.recordCount"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					/>
				</div>
			</div>
        </el-card>
        <!-- 修改弹窗 -->
		<el-dialog
            v-model="state.upShow"
            :title="state.detailData.id?'编辑':'添加数据组'"
            center
        >
            <div v-if="state.upShow">
            <el-form :model="state.detailData" ref="detailDataRef" :rules="rules" label-width="180px" status-icon>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="数据组名称" prop="name" >
                            <el-input v-model="state.detailData.name" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="数据字段(英文)" prop="config_name" >
                            <el-input v-model="state.detailData.config_name" :disabled="state.detailData.id?true:false"  clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="数据简介" prop="info" >
                            <el-input type="textarea" v-model="state.detailData.info" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="数类型" prop="cate_id" >
                            <el-radio-group v-model="state.detailData.cate_id">
                                <el-radio label="0"  border>默认</el-radio>
                                <el-radio label="3"  border>数据</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" >
                        <el-row v-for="(item, index) in state.detailData.fields" :key="index">
                            <el-col :span="8">
                                <el-form-item :label="'字段'+(index+1)" :prop="'fields.'+ index + '.name'" :rules="{required: true, message: '请输入字段名称：姓名', trigger: 'blur'}">
                                    <el-input v-model="item.name" placeholder="字段名称：姓名" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label-width="10px" :prop="'fields.'+ index + '.title'" :rules="{required: true, message: '请输入字段配置名', trigger: 'blur'}">
                                    <el-input v-model="item.title" placeholder="字段配置名：name" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label-width="10px" :prop="'fields.'+ index + '.type'" :rules="{required: true, message: '请选择字段类型', trigger: 'change'}">
                                    <el-select placeholder="字段类型" v-model="item.type">
                                        <el-option label="文本框" value="input"></el-option>
                                        <el-option label="多行文本框" value="textarea"></el-option>
                                        <el-option label="单选框" value="radio"></el-option>
                                        <el-option label="多选框" value="checkbox"></el-option>
                                        <el-option label="单图" value="upload"></el-option>
                                        <el-option label="多图" value="uploads"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="2">
                                <el-button type="danger"  @click="jsonBtn('del',index)" circle><i class="oneIcon fa fa-trash"></i></el-button>
                            </el-col>
                            <el-col :span="22" v-if="item.type=='radio'||item.type=='checkbox'">
                                <el-form-item :prop="'fields.'+ index + '.parameter'" :rules="{required: true, message: '请填写参数', trigger: 'change'}">
                                    <el-input type="textarea" placeholder="参数方式例如:
1=>男
2=>女
3=>保密" v-model="item.parameter" clearable />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="24">
                        <div class="k-text-center">
                            <el-button  @click="jsonBtn('add','')" >增加字段</el-button>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="state.upShow = false;state.btnloading=false;">取消</el-button>
                    <el-button type="primary" @click="queding" :loading="state.btnloading" :disabled="state.btnloading">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
    
<script lang="ts" setup name="maintainexploitgroup">
    import { toRefs,ref, reactive,onMounted, defineComponent } from 'vue';
    import { useRouter } from 'vue-router'
    import { ElNotification, ElMessage ,ElMessageBox ,FormRules,ElTree} from 'element-plus'
    import { isModification } from '/@/utils/kingmin';//去重
    import { systemApi } from '/@/api';

    const router = useRouter();
    const detailDataRef=ref();
    const state = reactive({
        roleBtn:router.currentRoute.value.meta.roleBtn,
        btnloading:false,
        loading:true,
        dataList:[],
        pages: {
            isAll: false,
            pageCount: 0,
            pageSize: 0,
            recordCount: 0,
            pno: 1
         },
        detailData:{},
        upShow:false,
        originalData:{},
        key:"",
    });
    const rules = reactive<FormRules>({
        info: [
            { required: true, message: '请填写数据提示', trigger: ['blur', 'change'] },
        ],
        name: [
            { required: true, message: '请填写名称', trigger: ['blur', 'change'] },
            { min: 2, max:12, message: '最少2个字符,最多12个字符', trigger: ['blur', 'change'] },
        ],
        config_name: [
            { required: true, message: '请填写字段', trigger: ['blur', 'change'] },
            { min: 4,  message: '最少4个字符 ', trigger: ['blur', 'change'] },
        ],
        fields: [
            { required: true, message: '请填写字段组', trigger: ['blur', 'change'] },
        ],
        order_num: [
            { required: true, message: '请填写分类排序', trigger: ['blur', 'change'] },
        ]
        
    });
    const queding=()=>{
        detailDataRef.value.validate((valid) => {
            if (valid) {
                // 修改
                let data=JSON.parse(JSON.stringify(state.detailData));
                state.btnloading=true;
                let dt={};
                if(state.detailData.id){
                    dt=isModification(data,state.originalData);
                    // let dt=state.detailData;
                    if(Object.values(dt).length>0){
                        dt.id=state.detailData.id;
                    }else{
                        ElMessage({message:'没有要修改的数据',type:"warning"});
                        state.upShow=false;
                        state.btnloading=false;
                        return false;
                    }
                    // console.log(dt)
                    upDataFun(dt);
                }else{
                    // console.log(data)
                    addDataFun(data);
                    
                }			
            }
        })
    }
    // 修改
    const upDataFun=(dt:object)=>{
        if(!dt){
            ElMessage.error('修改的数据为空');
            return false;
        }
        
        systemApi('upGroup',dt).then(res=>{
            ElMessage({message:res.msg?res.msg:"操作成功",type:"success"});
            state.upShow=false;
            state.btnloading=false;
             getGroupList();
        })
        .catch(res=>{
            if(res.code!=450000){
                ElMessageBox.confirm(res.msg, '提示', {
                    confirmButtonText: '确定1',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                .then(() => {})
                .catch(() => {});
                state.btnloading=false;
            }
        })
    }
    // 新增
    const addDataFun=(dt:object)=>{
        if(!dt){
            ElMessage.error('新增的数据为空');
            return false;
        }
        systemApi('addGroup',dt).then(res=>{
            ElMessage({message:res.msg?res.msg:"操作成功",type:"success"});
            state.upShow=false;
            state.btnloading=false;
            getGroupList();
        })
        .catch(res=>{
            if(res.code!=450000){
                ElMessageBox.confirm(res.msg, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                .then(() => {})
                .catch(() => {});
                state.btnloading=false;
            }
        })
    }
    const jsonBtn=(e:string,i:number)=>{
        if(e=='del'){
            state.detailData.fields.splice(i, 1);
        }
        if(e=='add'){
            state.detailData.fields.push(
                {
                    name:"",
                    title:"",
                    type:"",
                    parameter:"",
                }
            )
        }
    }
    const tabBtn=(e:string,item:object)=>{
        if(e=='add'){
            state.detailData={
                id:"",
                name:"",
                info:"",
                config_name:"",
                fields:[{
                    name:"",
                    title:"",
                    type:"",
                }],
                cate_id:"0"
            };
            state.upShow=true;
        }
        if(e=='editor'){
            state.detailData=item;
            state.originalData=JSON.parse(JSON.stringify(item));
            state.upShow=true;
        }
        if(e=='del'){
            ElMessageBox.confirm(
                '确定删除组合数据['+item.name+']吗?',
                '提示',
                {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
                }
            )
            .then(() => {
                let dt={
                    id:item.id,
                    isdel:1
                }
                upDataFun(dt);
                //  console.log(dt)
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消删除',
                })
            })
        }
    }
    // 获取管理员列表
    const getGroupList=(pno:string|number)=>{
        state.tbloading =true;
        if(!pno){
            pno=1;
        }
        const dt={
            pages:{
                pno:pno,
                pageSize:state.pages.pageSize
            },
            data:{
                key:state.key,
            }
        };
        systemApi('groupList',dt).then(res=>{
            state.dataList=res.list;
            state.pages=res.pages;
            state.tbloading=false;
            state.loading=false;
        })
    }
    const handleSizeChange = (val: number) => {
        state.pages.pageSize=val;
        getGroupList();
    }
    const handleCurrentChange = (val: number) => {
        getGroupList(val);
    }
    // 权限判断
    const isAuthBtn = (e) => {
        let auth=false;
        if(e){
            for(let p of state.roleBtn){
                if(p==e){
                    auth=true;
                }
            }
        }
        return auth;
    };
    // 跳转
    const tourl = (e) => {
        router.push(e);
    };
    
    onMounted(()=>{
          // 获取当前路由实例参数
        //   console.dir(router.currentRoute.value.query.id);
        //   console.dir(router.currentRoute.value.meta.roleBtn);
          if(!isAuthBtn('index')){
              router.push('/401');
          }else{
              //操作函数
              
              getGroupList();
          }
    })
</script>
    
<style scoped lang="scss">
    .maintainexploitgroup{
        padding:5px;
        .el-col {
            margin-bottom: 20px;
        }
    }
</style>
    